#include "DXInput.h"


int DXInput::Initialize()
{
	if (FAILED(DirectInput8Create(m_mainInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&m_lpdi,NULL)))
		return(0);

	if (!InitMouse())
		return (0);

	if (!InitKeyboard())
		return (0);
	return(1);
}

DXInput::DXInput(HINSTANCE mainInstance, HWND mainWnd)
{
	m_mainInstance = mainInstance;
	m_mainWnd = mainWnd;
	m_mousePoint.x = 0;
	m_mousePoint.y = 0;

	m_lpdi      = NULL;    // dxinput object
	m_lpdikey   = NULL;    // dxinput keyboard
	m_lpdimouse = NULL;    // dxinput mouse

}

int DXInput::InitMouse()
{
	// create a mouse device 
	if (m_lpdi->CreateDevice(GUID_SysMouse, &m_lpdimouse, NULL) != DI_OK)
		return(0);

	// set cooperation level
	// change to EXCLUSIVE FORGROUND for better control
	if (m_lpdimouse->SetCooperativeLevel(m_mainWnd, 
		DISCL_NONEXCLUSIVE | DISCL_BACKGROUND) != DI_OK)
		return(0);

	// set data format
	if (m_lpdimouse->SetDataFormat(&c_dfDIMouse) != DI_OK)
		return(0);

	// acquire the mouse
	if (m_lpdimouse->Acquire() != DI_OK)
		return(0);

	// return success
	return(1);
}

int DXInput::InitKeyboard()
{
	// create the keyboard device  
	if (m_lpdi->CreateDevice(GUID_SysKeyboard, &m_lpdikey, NULL) != DI_OK)
		return(0);

	// set cooperation level
	if (m_lpdikey->SetCooperativeLevel(m_mainWnd, 
		DISCL_NONEXCLUSIVE | DISCL_BACKGROUND)!=DI_OK)
		return(0);

	// set data format
	if (m_lpdikey->SetDataFormat(&c_dfDIKeyboard)!=DI_OK)
		return(0);

	// acquire the keyboard
	if (m_lpdikey->Acquire()!=DI_OK)
		return(0);

	// return success
	return(1);
}

int DXInput::GetKeyboardData()
{
	if (m_lpdikey)
	{
		if (m_lpdikey->GetDeviceState(256, (LPVOID)m_keyboardState) != DI_OK)
			return(0);
	}
	else
	{
		// keyboard isn't plugged in, zero out state
		memset(m_keyboardState,0,sizeof(m_keyboardState));

		// return error
		return(0);
	} 

	return(1);
}

int DXInput::GetMouseData()
{
	if (m_lpdimouse)    
	{
		if (m_lpdimouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&m_mouseState) != DI_OK)
			return(0);
	}
	else
	{
		// mouse isn't plugged in, zero out state
		memset(&m_mouseState,0,sizeof(m_mouseState));

		// return error
		return(0);
	}

	//ugly. but i don't know how to do it with dx since the dx's axis is relative.
	GetCursorPos(&m_mousePoint);
	return(1);
}

int DXInput::GetInputData()
{
	if (!GetKeyboardData())
		return 0;
	if (!GetMouseData())
		return 0;

	return 1;
}

void DXInput::ReleaseMouse()
{
	if (m_lpdimouse)
	{    
		m_lpdimouse->Unacquire();
		m_lpdimouse->Release();
	} 
}


void DXInput::ReleaseKeyboard()
{
	if (m_lpdikey)
	{
		m_lpdikey->Unacquire();
		m_lpdikey->Release();
	}
}

void DXInput::Release()
{
	ReleaseKeyboard();
	ReleaseMouse();
}

